package com.cy.helmet.utils;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;

import java.lang.reflect.Method;


/**
 * FloatTool.java:应用悬浮窗权限请求
 * <p>
 * AndroidMainifest.xml中添加： <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 * <p>
 * 用法：
 * 1、请求悬浮窗权限：FloatTool.RequestOverlayPermission(this);
 * 2、处理悬浮窗权限请求结果：FloatTool.onActivityResult(requestCode, resultCode, data, this);
 * -----
 * 2019-9-19 下午3:10:34
 * scimence
 */
public class FloatTool {
    public static boolean CanShowFloat = false;
    private static final int REQUEST_OVERLAY = 5004;

    /**
     * 动态请求悬浮窗权限
     */
    public static void RequestOverlayPermission(Activity Instatnce) {
        if (!canDrawOverlays(Instatnce)) {
            String ACTION_MANAGE_OVERLAY_PERMISSION = "android.settings.action.MANAGE_OVERLAY_PERMISSION";
            Intent intent = new Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + Instatnce.getPackageName()));
            Instatnce.startActivityForResult(intent, REQUEST_OVERLAY);
        } else {
            CanShowFloat = true;
        }
    }

    public static boolean canDrawOverlayViews(Activity con) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return true;
        }
        try {
            return Settings.canDrawOverlays(con);
        } catch (NoSuchMethodError e) {
            return canDrawOverlaysUsingReflection(con);
        }
    }
    public static boolean canDrawOverlays(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            return Settings.canDrawOverlays(context);
        } else {
            if (Settings.canDrawOverlays(context)) {
                return true;
            }
            try {
                WindowManager mgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                if (mgr == null) {
                    return false;
                }
                View viewToAdd = new View(context);
                WindowManager.LayoutParams params = new WindowManager.LayoutParams(0, 0,
                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSPARENT);
                viewToAdd.setLayoutParams(params);
                mgr.addView(viewToAdd, params);
                mgr.removeView(viewToAdd);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    }

    public static boolean canDrawOverlaysUsingReflection(Activity context) {
        try {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            Class clazz = AppOpsManager.class;
            Method dispatchMethod = clazz.getMethod("checkOp", new Class[]{int.class, int.class, String.class});
            int mode = (Integer) dispatchMethod.invoke(manager, new Object[]{24, Binder.getCallingUid(), context.getApplicationContext().getPackageName()});
            return AppOpsManager.MODE_ALLOWED == mode;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 浮窗权限请求，Activity执行结果，回调函数
     */
    public static void onActivityResult(int requestCode, int resultCode, Intent data, final Activity Instatnce) {
        // Toast.makeText(activity, "onActivityResult设置权限！", Toast.LENGTH_SHORT).show();
        if (requestCode == REQUEST_OVERLAY)        // 从应用权限设置界面返回
        {
            if (resultCode == Activity.RESULT_OK) {
                CanShowFloat = true;        // 设置标识为可显示悬浮窗
            } else {
                CanShowFloat = false;

//                if (!canDrawOverlayViews(Instatnce))    // 若当前未允许显示悬浮窗，则提示授权
//                {
//                    AlertDialog.Builder builder = new AlertDialog.Builder(Instatnce);
//                    builder.setCancelable(false);
//                    builder.setTitle("悬浮窗权限未授权");
//                    builder.setMessage("应用需要悬浮窗权限，以展示浮标");
//                    builder.setPositiveButton("去添加 权限", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                            RequestOverlayPermission(Instatnce);
//                        }
//                    });
//
//                    builder.setNegativeButton("拒绝则 退出", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                            // 若拒绝了所需的权限请求，则退出应用
//                            Instatnce.finish();
//                            System.exit(0);
//                        }
//                    });
//                    builder.show();
//                }
            }
        }
    }
}
